package com.shop.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.entity.dto.AdminImages.AdminImagesListDto;
import com.shop.entity.dto.AdminImages.AdminImagesRemoveDto;
import com.shop.entity.pojo.AdminUser;
import com.shop.entity.pojo.Images;
import com.shop.entity.pojo.Style;
import com.shop.entity.pojo.Wares;
import com.shop.admin.mapper.AdminUserMapper;
import com.shop.admin.mapper.ImagesMapper;
import com.shop.admin.mapper.StyleMapper;
import com.shop.admin.mapper.WaresMapper;
import com.shop.admin.service.ImagesService;
import com.shop.file.service.FileStorageService;
import com.shop.utils.common.enums.Code;
import com.shop.utils.common.enums.Message;
import com.shop.utils.common.enums.MessageConstant;
import com.shop.utils.common.result.PageResponseResult;
import com.shop.utils.common.result.Result;
import com.shop.utils.config.BaseContext;
import com.shop.utils.config.LoginFailedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service

public class ImagesServiceImpl extends ServiceImpl<ImagesMapper, Images> implements ImagesService {

    @Autowired
    private ImagesMapper imagesMapper;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WaresMapper waresMapper;
    @Autowired
    private StyleMapper styleMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;

    @Override
    public Result uploadPicture(MultipartFile file, String imagesName) {
        //1.检查参数
        if(file == null && file.getSize() == Message.Check_Int_Null){
            throw new LoginFailedException(MessageConstant.PARAM_REQUIRE);
        }
        List<Images> imagesList = imagesMapper.selectList(Wrappers.<Images>lambdaQuery().eq(Images::getName, imagesName));
        if (!CollectionUtils.isEmpty(imagesList)||imagesList.size()>Message.Check_Int_Null) {
            return Result.errorResult(Code.DATA_EXIST);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }

        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        //aa.jpg
        String originalFilename = file.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        Images waresImages=new Images();
        waresImages=waresImages.builder()
                .url(fileId)
                .name(imagesName)
                .saveAdmin(adminUser.getName())
                .saveTime(String.valueOf(LocalDateTime.now())).build();
        int save = imagesMapper.insert(waresImages);
        if (save==Message.Check_Int_False) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getWaresImagesList(AdminImagesListDto dto) {
        dto.checkParam();
        Page<Images> page=new Page(dto.getPage(),dto.getSize());
        Page<Images> value = imagesMapper.getAllByPage(page, dto);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) value.getTotal());
        result.setData(value.getRecords());
        return result;
    }

    @Override
    public Result removeWaresImages(AdminImagesRemoveDto dto) {
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        Long adminId = BaseContext.getCurrentId();
        AdminUser adminUser = adminUserMapper.selectById(adminId);
        if (adminUser==null||adminId==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        Images getWaresImages = imagesMapper.selectById(dto.getImagesId());
        if (getWaresImages==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        List<Wares> waresList = waresMapper.selectList(Wrappers.<Wares>lambdaQuery()
                .eq(Wares::getWaresImages, getWaresImages.getUrl()));
        List<Style> styleList = styleMapper.selectList(Wrappers.<Style>lambdaQuery()
                .eq(Style::getStyleImages, getWaresImages.getUrl()));
        if (!CollectionUtils.isEmpty(waresList)
                ||!CollectionUtils.isEmpty(styleList)
                ||waresList.size()> Message.Check_Int_Null
                ||styleList.size()>Message.Check_Int_Null) {
            return Result.errorResult(Code.PARAM_INVALID);
        }
        imagesMapper.remove(dto.getImagesId());
        fileStorageService.delete(getWaresImages.getUrl());
        return Result.okResult(Code.SUCCESS);
    }

}
